import os
import time
import random
import requests

from playwright.sync_api import Playwright, sync_playwright, expect


#PROMPT = 'sexy girl with awesome breast, 4k oil on linen by wlop, artgerm, andrei riabovitchev, nuri iyem, james gurney, james jean, greg rutkowski, highly detailed, soft lighting'
f_idx = 'idx.txt'


def set_cur_idx(idx):
    with open(f_idx, 'w+') as wp:
        wp.write(f'{idx}')


def get_cur_idx():
    if not os.path.exists(f_idx):
        set_cur_idx('0')
    with open(f_idx, 'r') as rp:
        return int(rp.read().strip())


def gen_prompts():
    """生成prompts"""
    main = '%s %s with %s %s'
    adjs = ['beautiful', 'cute', 'sexy', 'pretty', 'fine']
    objs = ['girl', 'woman', 'lady', 'beauty', 'model']
    adj2 = ['awesome', 'wonderful', 'amazing', 'great', 'superb', 'admirable', 'excellent', 'fantastic', 'splendid', 'unexceptionable', 'suitable']
    nons = ['dress', 'glass', 'hat', 'skirt', 'bikini', 'hair', 'breast', 'underwear']
    return [main % (adj, obj, ad2, non) for adj in adjs for obj in objs for ad2 in adj2 for non in nons]


def gen_headers(content_type='', **kwargs):
    """生成headers"""
    if content_type == 'json':
        content_type = "application/json"
    else:
        content_type = "application/x-www-form-urlencoded; charset=UTF-8"
    headers = {"Content-Type": content_type}
    headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36'
    headers['origin'] = 'https://www.mage.space'
    headers['referer'] = 'https://www.mage.space/'
    for key, val in kwargs.items():
        headers[key] = val
    return headers


def my_request(method, url, headers=None, data=None, proxies=None):
    """
    封装requests
    @param body: json格式的data
    """
    if isinstance(data, dict):
        data = json.dumps(data).encode('utf-8')
    return requests.request(method, url, headers=headers, data=data, proxies=proxies)


def download(img_url, fname=''):
    output = 'stable_downloads'
    if not os.path.exists(output):
        os.makedirs(output)

    if not fname:
        fname = img_url.rsplit('/', 1)[-1]
    for ch in r'\/:*?"<>|':
        fname = fname.replace(ch, '.')
    if not img_url.lower().endswith('.jpg') and \
        not img_url.lower().endswith('.jpeg') and \
        not img_url.lower().endswith('.png'):
        fname += '.jpg'
    fullpath = f'{output}/{fname}'
    if os.path.exists(fullpath):
        return fullpath

    headers = gen_headers()
    resp = my_request('get', img_url, headers)
    if resp.status_code == 200:
        # 创建文件保存图片
        with open(fullpath, 'wb') as writer:
            # 将图片字节码写入创建的文件中
            writer.write(resp.content)
        print(f'图片已下载到：{fullpath}')
    else:
        print(f'ERROR: 下载{img_url}失败!')
        return ''


def run(playwright: Playwright, prompt) -> None:
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()

    # Open new page
    page = context.new_page()

    # Go to https://www.mage.space/
    page.goto("https://www.mage.space/")
    
    time.sleep(3)

    print('Start generating image...')
    # Click text=create anythingView OptionsCancelaspect ratioLandscape (3:2)Square (1:1)Phone (2 >> textarea
    page.locator("text=create anythingView OptionsCancelaspect ratioLandscape (3:2)Square (1:1)Phone (2 >> textarea").click()

    full_prompt = f'{prompt} 4k oil on linen by wlop, artgerm, andrei riabovitchev, nuri iyem, james gurney, james jean, greg rutkowski, highly detailed, soft lighting'
    # Fill text=create anythingView OptionsCancelaspect ratioLandscape (3:2)Square (1:1)Phone (2 >> textarea
    page.locator("text=create anythingView OptionsCancelaspect ratioLandscape (3:2)Square (1:1)Phone (2 >> textarea").fill(full_prompt)

    # Click .mantine-UnstyledButton-root.mantine-ActionIcon-root.mantine-1npn6ro
    page.locator(".mantine-UnstyledButton-root.mantine-ActionIcon-root.mantine-1npn6ro").click()

    time.sleep(60)

    print('Start enhancing image...')
    try:
        # Click button:has-text("Enhance")
        page.locator("button:has-text(\"Enhance\")").click()
    except Exception as e:
        print(e)
        context.close()
        browser.close()

    time.sleep(60)

    print('Start downloading image...')
    # Click div[role="dialog"] a div:has-text("Download")
    with page.expect_download() as download_info:
        page.locator("div[role=\"dialog\"] a div:has-text(\"Download\")").click()
    download_info = download_info.value
    fname = f'{prompt}_{download_info.suggested_filename}'
    print(download_info.url, fname)
    download(download_info.url, fname)

    time.sleep(60)
    # expect(page).to_have_url("https://www.mage.space/")

    # ---------------------
    context.close()
    browser.close()


start_idx = get_cur_idx()
prompts = gen_prompts()

with sync_playwright() as playwright:
    for i, prompt in enumerate(prompts[start_idx+1:]):
        try:
            print('=' * 100)
            print(start_idx+1+i, prompt)
            run(playwright, prompt)
            set_cur_idx(start_idx+1+i)
            print('-' * 100)
        except Exception as e:
            print(e)


#download('https://cdn.mage.space/enhanced/ceee7794128f4012abe881ae1f922f06.png')

